package cn.com.connext.scrm.service;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.MdmHelpMsgRepository;
import cn.com.connext.scrm.repository.master.MiniProgramUserRepository;
import cn.com.connext.scrm.repository.master.MsgTemplateInfoRepository;
import cn.com.connext.scrm.repository.master.PrizeRepository;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.dto.PointDTO;
import cn.com.connext.scrm.service.dto.PrizeDTO;
import cn.com.connext.scrm.service.mapper.PrizeMapper;
import cn.com.connext.scrm.utils.DateUtils;
import cn.com.connext.scrm.utils.HttpUtils;
import cn.com.connext.scrm.utils.wdtutils.StringUtils;
import cn.com.connext.scrm.utils.wechat.WxMessageSend;
import cn.com.connext.scrm.web.rest.vm.MdmHelpMsgVM;
import cn.com.connext.scrm.web.rest.vm.MdmReturnVM;
import cn.com.connext.scrm.web.rest.vm.Template;
import cn.com.connext.scrm.web.rest.vm.TemplateParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/***
 *  created by wangzhan on 2018/01/24
 *
 *  小程序 活动管理
 */
@Service
@Transactional
public class MdmHelpMsgService {

    private final Logger log = LoggerFactory.getLogger(MdmHelpMsg.class);
    @Autowired
    private MdmHelpMsgRepository mdmHelpMsgRepository;
    @Autowired
    private MdmHelpActivityService mdmHelpActivityService;
    @Autowired
    private MdmHelpFullCallService mdmHelpFullCallService;
    @Autowired
    private MiniProgramUserRepository miniProgramUserRepository;
    @Autowired
    private WxAPIService wxAPIService;

    @Autowired
    private PrizeRepository prizeRepository;
    @Autowired
    private PrizeService prizeService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private PrizeGoodService prizeGoodService;
    @Autowired
    private MdmTemplateConfirmService mdmTemplateConfirmService;
    @Autowired
    private PrizeMapper prizeMapper;

    @Autowired
    private AccessTokenImpl accessTokenImpl;
    @Autowired
    private WxMessageSend wxMessageSend;
    @Autowired
    private MsgTemplateInfoRepository msgTemplateInfoRepository;


    private Lock lock = new ReentrantLock();
    public JsonResult save(MdmHelpMsgVM req) {
        JsonResult result =new JsonResult();
        if(req ==null || StringUtils.isEmpty(req.getHelpUnionId())|| StringUtils.isEmpty(req.getCreateUnionId())|| req.getMdmHelpActivityId()==null ||  req.getActivityId()==null || StringUtils.isEmpty(req.getOpenId())){
            result.setMessage("参数信息不能为空!");
            result.setState(-1);
        }else{
            ZonedDateTime now = ZonedDateTime.now();
            req.setCreateTime(now);
            MdmHelpMsg entity = new MdmHelpMsg();
            try{
                lock.lock();
                // todo 防止重复助力领取奖品
                MdmHelpMsg msgEntity = mdmHelpMsgRepository.findByMdmHelpActivityIdAndCreateUnionIdAndHelpUnionId(req.getMdmHelpActivityId(),req.getCreateUnionId(),req.getHelpUnionId());
                if(msgEntity !=null){
                    result.setMessage("您已参与过好友发起的邀请!");
                    result.setState(-1);
                    return result;
                }
                MiniProgramUser user =  miniProgramUserRepository.findByUnionId(req.getHelpUnionId());
                //校验助力用户信息
                if(user ==null || StringUtils.isEmpty(user.getPhone())){
                    result.setState(-1);
                    result.setMessage("用户信息异常!");
                    return result;
                }
                MdmHelpActivity one = mdmHelpActivityService.findOne(req.getMdmHelpActivityId());
                //校验活动是否开启
                if(one.getIsOpen() ==2){
                    result.setState(-1);
                    result.setMessage("该活动暂未开启!");
                    return result;
                }
                //添加add 严重 防止助力完成后 再次提交助力
                List<MdmHelpMsg> listCount = mdmHelpMsgRepository.findByMdmHelpActivityIdAndCreateUnionId(req.getMdmHelpActivityId(), req.getCreateUnionId());
                if (one.getHelpPeopleCount() <= listCount.size()) {
                    result.setState(-1);
                    result.setMessage("助力人数已满!");
                    return result;
                }
                //校验活动是否开启
                long currentTime = ZonedDateTime.now().toInstant().getEpochSecond() / 60;
                long startTime = one.getStartTime().toInstant().getEpochSecond() / 60;
                long endTime = one.getEndTime().toInstant().getEpochSecond() / 60;
                if(currentTime < startTime || currentTime >endTime){
                    result.setState(-1);
                    result.setMessage("不在活动有效时间内!");
                    return result;
                }
                BeanUtils.copyProperties(req,entity);
                mdmHelpMsgRepository.saveAndFlush(entity);
//               List<MdmHelpMsg> helpUserList =mdmHelpMsgRepository.findByHelpUnionId(entity.getHelpUnionId());
//               if(helpUserList.size() >0){
//                   result.setState(-1);
//                   result.setMessage("只能助力1次");
//                   return result;
//               }
                List<MdmHelpMsg> list = mdmHelpMsgRepository.findByMdmHelpActivityIdAndCreateUnionId(req.getMdmHelpActivityId(), req.getCreateUnionId());
                log.info("当前助力总数--" +list.size());
                log.info("活动设置总助力人数--" +one.getHelpPeopleCount());
                if(list !=null && list.size() >0){
                    if(one !=null){
                        if(one.getHelpPeopleCount() == list.size()){
                            result = RecordPrizeAndStock(req.getMdmHelpActivityId(),req.getCreateUnionId(),null,req.getActivityId(),one.getFinishGoodId(),1,req.getOpenId(),one.getActivityName());
                            //此处添加助力完成调用微信订阅消息发送
                            if (result.getState() == 0) {
                                Prize prize = JSON.parseObject(JSON.toJSONString( result.getData()), Prize.class);
                                //助力完成发送用户信息
                                this.verifyHelpDetails(one,entity,"1",req
                                .getActivityId(),prize.getId());
                            }
                        }
                        result = RecordPrizeAndStock(null,req.getHelpUnionId(),req.getCreateUnionId(),req.getActivityId(),one.getHelpGoodId(),2,req.getOpenId(),null);
                        //此处添加助力成功调用微信订阅消息发送
                        if (result.getState() == 0) {
                            Prize prize = JSON.parseObject(JSON.toJSONString(result.getData()), Prize.class);
                            this.verifyHelpDetails(one,entity,"0",req
                                .getActivityId(),prize.getId());
                        }
                    }
                }
            }catch (Exception e){
                log.error(e.getMessage());
            }finally {
                lock.unlock();
            }
        }
        return result;
    }

    /**
     * 查询会员是否存在
     * @param unionId
     * @param mobile
     * @return
     */
    public JsonResult getMember(String unionId,String mobile){
        JsonResult result = new JsonResult();
        if (StringUtils.isEmpty(unionId)&&StringUtils.isEmpty(mobile)) {
            result.setState(-1);
            result.setMessage("参数异常!");
            return result;
        }

        Member member = memberService.getMemberByUnionIdOrMobile(unionId, mobile);
        if (null != member&&!StringUtils.isEmpty(mobile)&&mobile.equals(member.getMobile())) {
            result.setState(-1);
            result.setMessage("当前手机号已注册会员");
            return result;
        }
        return  result;
    }

    /**
     * 验证助力信息
     * @param one 助力数据信息
     * @param entity 当前助力信息数据
     * @param helpFlag 助力是否完成标识， 1 完成 0 未完成
     */
    public void verifyHelpDetails(MdmHelpActivity one, MdmHelpMsg entity, String helpFlag,String activityId,Integer prizeId){
        log.info("验证助力信息start-------------------------");
        if (null == one) {
            log.info("verifyHelpDetails 验证助力信息 对象为null");
        }
        //验证是否开启了订阅通知
        if (null != one.getIsMessage() && 1 == one.getIsMessage()) {

//            Set<String> strings = Sets.newConcurrentHashSet();
            //助力人unionId
            String helpUnionId = entity.getHelpUnionId();
            //助力发起人unionId
            String createUnionId = entity.getCreateUnionId();
            // 根据unionId 查询member 取openId
            Member helpUnionMem = memberService.findByUnionId(helpUnionId);
            Member createUnionMem = memberService.findByUnionId(createUnionId);
            String openId = createUnionMem.getOpenId();

            List<TemplateParam> templateParams = new ArrayList<>();

            PrizeGood prizeGood ;
            if ("1".equals(helpFlag)) {
                prizeGood = prizeGoodService.findById(one.getFinishGoodId());
            } else if ("0".equals(helpFlag)) {
                prizeGood = prizeGoodService.findById(one.getHelpGoodId());
            } else {
                prizeGood = null;
            }
            //组装提醒参数
//            PrizeGood prizeGood = prizeGoodService.findById(one.getFinishGoodId());
            TmpMsgRecord record = new TmpMsgRecord();
            record.setGood_type(prizeGood.getType());
            record.setPrizeId(prizeId);
            record.setCreateTime(new Date());
            record.setExpireTime(prizeGood.getExpireDate());
            record.setExpireCallDate(prizeGood.getExpireCallDate());
            record.setActivityId(activityId);
            record.setGoodId(prizeGood.getId());
            record.setOpenId(openId);
            record.setGoodName(org.apache.commons.lang3.StringUtils.isNotBlank(one.getHelpMdmName())?one.getHelpMdmName():prizeGood.getGoodName());
            record.setHelpGoodRemark(one.getPrizeExpireMessageRemark());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(one.getPrizeExpireMessage())) {
                record.setExpireTemplateId(one.getPrizeExpireMessage());
                record.setIsExpireMessage(1);
            }
//            if (org.apache.commons.lang3.StringUtils.isNotBlank(one.getWinMessage())) {
//                record.setPrizeTemplateId(one.getWinMessage());
//            }
            if ("1".equals(helpFlag)) {

                if (!StringUtils.isEmpty(one.getHelpEndMessage())) {
                    //临时处理活动名称超长导致发送失败问题
                    String activityName = one.getActivityName();
                    if (activityName.length() > 20) {
                        templateParams.add(new TemplateParam("thing1", StringUtils.isEmpty(one.getHelpMdmName())?activityName.substring(0,20):one.getHelpMdmName()));
                    } else {
                        templateParams.add(new TemplateParam("thing1",StringUtils.isEmpty(one.getHelpMdmName())?activityName:one.getHelpMdmName()));
                    }
                    templateParams.add(new TemplateParam("thing2", StringUtils.isEmpty(one.getHelpMessageRemark())?"您发起的助力已成功完成，请查看你的奖品":one.getHelpMessageRemark()));

                    wxMessageSend.sendMessageWx("page/reward/activityHistory/index",one.getHelpEndMessage(),openId,templateParams,record);
                } else {
                    log.info("未维护助力完成模板id，不发送订阅消息，活动id：{}",one.getId());
                }

                //添加助力人发起人发送奖品信息
                if (!StringUtils.isEmpty(one.getWinMessage())) {
                    //临时处理活动名称超长导致发送失败问题
                    String activityName = one.getActivityName();
                    if (activityName.length() > 20) {
                        templateParams.add(new TemplateParam("thing1", StringUtils.isEmpty(one.getHelpMdmName())?activityName.substring(0,20):one.getHelpMdmName()));
                    } else {
                        templateParams.add(new TemplateParam("thing1",StringUtils.isEmpty(one.getHelpMdmName())?activityName:one.getHelpMdmName()));
                    }
                    templateParams.add(new TemplateParam("thing2", StringUtils.isEmpty(one.getWinMessageRemark())?"恭喜你获得以上奖品":one.getWinMessageRemark()));
                    wxMessageSend.sendMessageWx("page/reward/activityHistory/index",one.getHelpEndMessage(),openId,templateParams,record);
                }

            } else if ("0".equals(helpFlag)) {

                if (!StringUtils.isEmpty(one.getHelpMessage())) {
                    templateParams.add(new TemplateParam("thing1",helpUnionMem.getAccount()));
                    //临时处理活动名称超长导致发送失败问题
                    String activityName = one.getActivityName();
                    if (activityName.length() > 20) {
                        templateParams.add(new TemplateParam("thing2", StringUtils.isEmpty(one.getHelpMdmName())?activityName.substring(0,20):one.getHelpMdmName()));
                    } else {
                        templateParams.add(new TemplateParam("thing2",StringUtils.isEmpty(one.getHelpMdmName())?activityName:one.getHelpMdmName()));
                    }
                    templateParams.add(new TemplateParam("thing2",StringUtils.isEmpty(one.getHelpMdmName())?activityName:one.getHelpMdmName()));
                    templateParams.add(new TemplateParam("thing3",StringUtils.isEmpty(one.getHelpMessageRemark())?"好友为您助力成功":one.getHelpMessageRemark()));

                    wxMessageSend.sendMessageWx("page/reward/activityHistory/index",one.getHelpMessage(),openId,templateParams,null);
                } else {
                    log.info("未维护助力通知模板id，不发送订阅消息，活动id：{}",one.getId());
                }

                if (!StringUtils.isEmpty(one.getFriendWinMessage())) {
                    List<TemplateParam> friendTemplateParams = new ArrayList<>();
                    String[] str =new String[]{"thing1","date2","thing3"};
                    friendTemplateParams.add(new TemplateParam(str[0],
                        org.apache.commons.lang3.StringUtils.isNotBlank(one.getHelpMdmName())?one.getHelpMdmName():prizeGood.getGoodName()));
                    friendTemplateParams.add(new TemplateParam(str[1],
                        DateUtils.getStringToYYYYMMDD(new Date())));
                    friendTemplateParams.add(new TemplateParam(str[2],
                        org.apache.commons.lang3.StringUtils.isNotBlank(
                            one.getFriendPrizeExpireMessageRemark())?one.getFriendPrizeExpireMessageRemark():"恭喜您获得以上奖品"));

                    TmpMsgRecord friendRecord = new TmpMsgRecord();
                    friendRecord.setGood_type(prizeGood.getType());
                    friendRecord.setPrizeId(prizeId);
                    friendRecord.setCreateTime(new Date());
                    friendRecord.setExpireTime(prizeGood.getExpireDate());
                    friendRecord.setExpireCallDate(prizeGood.getExpireCallDate());
                    friendRecord.setActivityId(activityId);
                    friendRecord.setGoodId(prizeGood.getId());
                    friendRecord.setOpenId(helpUnionMem.getOpenId());
                    friendRecord.setGoodName(org.apache.commons.lang3.StringUtils.isNotBlank(one.getHelpMdmName())?one.getHelpMdmName():prizeGood.getGoodName());
                    friendRecord.setHelpGoodRemark(one.getPrizeExpireMessageRemark());
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(one.getFriendWinMessage())) {
                        friendRecord.setExpireTemplateId(one.getFriendWinMessage());
                        friendRecord.setIsExpireMessage(1);
                    }
                    wxMessageSend.sendMessageWx("page/reward/activityHistory/index",one.getFriendWinMessage(),helpUnionMem.getOpenId(),friendTemplateParams,friendRecord);

                } else {
                    log.info("未维护好友助力通知 不通知给助力人订阅消息：",one.getId());
                }

            } else {
                log.info("未知状态");
            }
        } else {
            log.info("verifyHelpDetails  订阅通知未开启不发送订阅消息");
        }

    }

    private JsonResult RecordPrizeAndStock(Long mdmHelpActivityId,String unionId,String createUnionId, String activityId,Integer goodId,Integer num,String openId,String activityName) {
        JsonResult result = new  JsonResult();
        Boolean flag = prizeService.cutStock(goodId, activityId);
        if (!flag) {
            result.setState(-1);
            result.setMessage("系统繁忙,库存不足");
            return result;
        }
        Prize prize = new Prize();
        prize.setUnionId(unionId);
        //奖品ID
        prize.setGoodId(goodId);
        prize.setCreateTime(new Date());
        prize.setUpdateTime(new Date());
        prize.setAddPoint(false);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(activityId)) {
            prize.setActivityId(activityId);
        }
        Prize prize1 = prizeRepository.saveAndFlush(prize);
        //通过奖品ID获取当前时间的奖品
        PrizeGood good = prizeGoodService.findById(goodId);
        PrizeDTO dto = prizeMapper.toDto(prize1);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getGoodName())) {
            dto.setGoodName(good.getGoodName());
        }
        dto.setType(good.getType());
        //增加奖品图片
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getGoodImg())) {
            dto.setGoodImg(good.getGoodImg());
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getGoodImg())) {
            dto.setPagePath(good.getPagePath());
        }
        if (null != good.getPoint()) {
            dto.setPoint(good.getPoint());
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getCardId())) {
            dto.setCardId(good.getCardId());
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getCode())) {
            dto.setCode(good.getCode());
        }
        log.info("dto:{}", dto.toString());

        dto.setButtonText(good.getButtonText());

        if (good.getRemark()!=null){
            dto.setRemark(good.getRemark());
        }

        if (good.getPathType()!=null){
            dto.setPathType(good.getPathType());
        }
        if (good.getAppId()!=null){
            dto.setAppId(good.getAppId());
        }
        if (good.getType() == 0) {
            if (good.getPoint() == null || good.getPoint() == 0) {
                good.setPoint(50);
            }
        }
        final Integer prizeId = prize.getId();
        if (good.getType() == 0) {
            ExecutorService service = Executors.newSingleThreadExecutor();
            service.execute(() -> {
                addPoint(unionId, good.getPoint(), prizeId);
                log.info("加分结束");
            });
        }
        if(num == 1){
            //已满,添加到窗口提示，状态isCall =1 需要提示
            MdmHelpFullCall mdmHelpFullCall = new MdmHelpFullCall();
            mdmHelpFullCall.setCreateTime(ZonedDateTime.now());
            mdmHelpFullCall.setCreateUnionId(unionId);
            mdmHelpFullCall.setIsCall(1);
            mdmHelpFullCall.setMdmHelpActivityId(mdmHelpActivityId);
            mdmHelpFullCall.setPrizeId(prize1.getId());
            mdmHelpFullCallService.save(mdmHelpFullCall);
            sendTemplate(openId,activityName,mdmHelpActivityId);
            result.setMessage("恭喜您已完成助力获得"+good.getGoodName()+"礼品");
            result.setState(0);
        }else{
            Member m = memberService.findByUnionId(createUnionId);
            dto.setNickName(m.getNickName());
            result.setMessage("恭喜您已助力成功获得"+good.getGoodName()+"礼品");
            result.setState(0);
        }
        result.setData(dto);
        return result;
    }

    public JsonResult findByActivityIdAndCreateUserId(MdmHelpMsg req) {
        JsonResult result =new JsonResult();
        if(req ==null){
            result.setMessage("用户参数不能为空!");
            result.setState(-1);
        }else{
            if(StringUtils.isEmpty(req.getCreateUnionId()) || req.getMdmHelpActivityId() ==null){
                result.setMessage("用户参数不能为空!");
                result.setState(-1);
                return result;
            }else{
                List<MdmHelpMsg> list =  mdmHelpMsgRepository.findByMdmHelpActivityIdAndCreateUnionId(req.getMdmHelpActivityId(),req.getCreateUnionId());
                MdmHelpActivity activity = mdmHelpActivityService.findOne(req.getMdmHelpActivityId());
                if(activity ==null){
                    result.setMessage("不存在此活动!");
                    result.setState(-1);
                    return result;
                }
                MdmReturnVM vm = new MdmReturnVM();
                vm.setMdmHelpActivity(activity);
                List<String> unionIdList = new ArrayList<>();
                if(list !=null && list.size() >0){
                    for (MdmHelpMsg msg:list ) {
                        unionIdList.add(msg.getHelpUnionId());
                    }
                    if(activity.getIsOpen() ==2){
                        result.setMessage("该助力活动暂未开启!");
                        result.setState(-1);
                        return result;
                    }else {
                        List<MiniProgramUser> memberList = miniProgramUserRepository.findUserMsg(unionIdList);
                        vm.setList(memberList);
                    }
                }
                PrizeGood good = prizeGoodService.findById(activity.getHelpGoodId());
                PrizeGood finishGood = prizeGoodService.findById(activity.getFinishGoodId());
                vm.setFinishGood(finishGood);
                vm.setGood(good);
                List<MdmTemplateConfirm> confimlist = mdmTemplateConfirmService.findByMdmHelpActivityIdAndCreateUnionId(req.getMdmHelpActivityId(),req.getCreateUnionId());
                if(confimlist !=null && confimlist.size() >0){
                    vm.setConfirmTemplate(true);
                }else{
                    vm.setConfirmTemplate(false);
                }
                result.setData(vm);
                result.setState(0);
            }
        }
        return result;
    }

    public JsonResult sendTemplate(String openId,String activityName,Long mdmHelpActivityId) {
        log.info("进入订阅消息，参数openId ="+openId+",参数活动名称="+activityName);
        JsonResult result = new JsonResult();
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
        String Access_Token = wxAPIService.getThisAccessToken();
        Date d = new Date();
        Template template = new Template();
        template.setTemplate_id(Constants.MDMTEMPLATEID);
        template.setTouser(openId);
        String page = "page/mgm/index?id=mdmHelpActivityId";
        String resultpage = page.replace("mdmHelpActivityId", String.valueOf(mdmHelpActivityId));
        template.setPage(resultpage);
        List<TemplateParam> paras = new ArrayList<TemplateParam>();

        paras.add(new TemplateParam("thing1", "会员邀好友活动"));
//        //测试
//        paras.add(new TemplateParam("thing2", "您的助力已完成，请及时领取助力礼包"));
        //生产            yyyy年MM月dd日HH时mm分ss秒                                   2019年10月16日12时18分00秒
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String formatTime = sdf.format(new Date());
        log.info("进入订阅消息，时间格式化结果 ="+formatTime);
        paras.add(new TemplateParam("date2", formatTime));
        template.setTemplateParamList(paras);
        requestUrl=requestUrl.replace("ACCESS_TOKEN", Access_Token);
        String resultString = HttpUtils.doPost(requestUrl, template.toJSON());
        JSONObject jsonResult = JSONObject.parseObject(resultString);
        log.info("执行完订阅消息返回 ="+jsonResult);
        if (jsonResult != null) {
            System.out.println(jsonResult);
            int errorCode = jsonResult.getInteger("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                result.setMessage("Send Success");
                result.setState(0);
            } else {
                result.setMessage("订阅消息发送失败:" + errorCode + "," + errorMessage);
                result.setState(1);
            }
        } else {
            result.setMessage("订阅消息发送失败:jsonResult为空");
            result.setState(1);
        }
        //  tmpMsgRecordService.batchAdd(tmList);
        return result;
    }

    public JsonResult findIsNeedPrompt(MdmHelpMsg req) {
        JsonResult result = new JsonResult();
        if (req == null || StringUtils.isEmpty(req.getCreateUnionId()) || req.getMdmHelpActivityId() == null) {
            result.setMessage("用户参数不能为空!");
            result.setState(-1);
            return result;
        } else {
            //todo 为提示发起助力人未中奖改动
            MdmHelpActivity one = mdmHelpActivityService.findOne(req.getMdmHelpActivityId());
            List<MdmHelpMsg> list = mdmHelpMsgRepository.findByMdmHelpActivityIdAndCreateUnionId(req.getMdmHelpActivityId(), req.getCreateUnionId());
            log.info("当前助力总数--" +list.size());
            log.info("活动设置总助力人数--" +one.getHelpPeopleCount());
            if(list ==null || one.getHelpPeopleCount() > list.size()){
                result.setMessage("不需要提示!");
                result.setState(-1);
                return result;
            }

            MdmHelpFullCall mdmHelpFullCall = mdmHelpFullCallService.findByCreateUnionIdAndMdmHelpActivityId(req.getCreateUnionId(), req.getMdmHelpActivityId());
            if (mdmHelpFullCall == null) {
                result.setMessage("活动奖励已发放完毕，敬请关注后续精彩活动!");
                result.setState(1);
                return result;
            } else if (mdmHelpFullCall.getIsCall() == 2) {
                result.setMessage("不需要提示!");
                result.setState(-1);
                return result;
            } else {
                mdmHelpFullCallService.updateByCreateUnionIdAndMdmHelpActivityId(req.getCreateUnionId(), req.getMdmHelpActivityId());
                PrizeGood good = prizeGoodService.findById(one.getFinishGoodId());
                Prize prize = new Prize();
                prize.setUnionId(req.getCreateUnionId());
                //奖品ID
                prize.setGoodId(one.getFinishGoodId());
                prize.setCreateTime(new Date());
                prize.setUpdateTime(new Date());
                prize.setAddPoint(false);
                prize.setId(mdmHelpFullCall.getPrizeId());
//                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(req.queryByBackgetActivityId())) {
//                        prize.setActivityId(req.getActivityId());
//                    }
                PrizeDTO dto = prizeMapper.toDto(prize);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getGoodName())) {
                    dto.setGoodName(good.getGoodName());
                }
                dto.setType(good.getType());
                //增加奖品图片
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getGoodImg())) {
                    dto.setGoodImg(good.getGoodImg());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getGoodImg())) {
                    dto.setPagePath(good.getPagePath());
                }
                if (null != good.getPoint()) {
                    dto.setPoint(good.getPoint());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getCardId())) {
                    dto.setCardId(good.getCardId());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getCode())) {
                    dto.setCode(good.getCode());
                }
                // 增加日期：2021-12-20 原因：补充核销券信息
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getCouponType())) {
                    dto.setCouponType(good.getCouponType());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getMgmUrl())){
                    dto.setMgmUrl(good.getMgmUrl());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getMgmButtonName())){
                    dto.setMgmButtonName(good.getMgmButtonName());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getMgmStatus())){
                    dto.setMgmStatus(good.getMgmStatus());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getQrCodeId())){
                    dto.setQrCodeId(good.getQrCodeId());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getHxContent1())){
                    dto.setHxContent1(good.getHxContent1());
                }
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(good.getHxContent2())){
                    dto.setHxContent2(good.getHxContent2());
                }

                log.info("dto:{}", dto.toString());

                dto.setButtonText(good.getButtonText());

                if (good.getRemark() != null) {
                    dto.setRemark(good.getRemark());
                }

                if (good.getPathType() != null) {
                    dto.setPathType(good.getPathType());
                }
                if (good.getAppId() != null) {
                    dto.setAppId(good.getAppId());
                }
                result.setData(dto);
                result.setMessage("恭喜您已助力成功获得" + good.getGoodName() + "礼品");
                result.setState(0);
                return result;
            }
        }
    }

    public JsonResult checkUserIsExist(MdmHelpMsgVM req) {
        JsonResult result =new JsonResult();
        if(req ==null || StringUtils.isEmpty(req.getHelpUnionId())){
            result.setMessage("用户参数不能为空!");
            result.setState(-1);
        }else{
//            if(req.getCreateUnionId() ==req.getHelpUnionId()){
//                result.setMessage("您进入的是自己的!");
//                result.setState(-1);
//            }
            Member member = memberService.findByUnionId(req.getHelpUnionId());
            if(member ==null || StringUtils.isEmpty(member.getMobile())){
                result.setMessage("该用户为新客，可以参与助力!");
                result.setState(0);
            }else{
                MdmHelpMsg msgEntity = mdmHelpMsgRepository.findByMdmHelpActivityIdAndCreateUnionIdAndHelpUnionId(req.getMdmHelpActivityId(),req.getCreateUnionId(),req.getHelpUnionId());
                if(msgEntity !=null){
                    result.setMessage("您已参与过好友发起的邀请!");
                    result.setState(-1);
                }else{
                    result.setMessage("您已是帝亚吉欧会员,发起自己的邀请立享惊喜!");
                    result.setState(-1);
                }
            }
        }
        return result;
    }

    public void addPoint(String memberShipId, Integer addPoint, Integer prizeId) {
        String accessToken = accessTokenImpl.getAccessToken();
        String requestUrl = Constants.PointIncr.replace("MEMBERSHIP", memberShipId).replace("ACCESSTOKEN", accessToken);
        PointDTO dto = new PointDTO();
        Date currentTime = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentTime);
        calendar.add(Calendar.HOUR, -8);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String timeStamp = formatter.format(calendar.getTime());
        dto.setContentName("主力活动积分奖品获得");
        dto.setSource("帝亚吉欧会员俱乐部");
        dto.setDate(timeStamp);
        dto.setPattern(4);
        dto.setPoint(addPoint);
        OkHttpClient client = new OkHttpClient().newBuilder()
            .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(dto));
        Request request = new Request.Builder()
            .url(requestUrl)
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .build();
        try {
            Response response = client.newCall(request).execute();
            String result = new String(response.body().bytes());
            log.info("调用加分接口,返回值:{}", result);
            Prize prize = prizeRepository.findOne(prizeId);
            prize.setAddPoint(true);
            Prize prize1 = prizeRepository.saveAndFlush(prize);
            log.info("加分操作完,prize1:{}", prize1.getAddPoint());
            response.body().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询助力活动奖品发放情况
     */
    public JsonResult findMdmHelpActivityPrize(MdmHelpMsgVM vm) {
        JsonResult result =new JsonResult();
        if(vm ==null || StringUtils.isEmpty(vm.getHelpUnionId())|| vm.getUserType() == null || vm.getMdmHelpActivityId() == null){
            result.setMessage("查询助力活动奖品发放情况参数不能为空!");
            result.setState(-1);
            return result;
        }else{
            MdmHelpActivity activity = mdmHelpActivityService.findOne(vm.getMdmHelpActivityId());
            //用户类型0（发起人）、1（助力人)
            if (vm.getUserType() == 0) {
                Integer finishGoodId = activity.getFinishGoodId();
                List<Prize> list = prizeRepository.findByUnionIdAndGoodId(vm.getHelpUnionId(), finishGoodId);
                if (CollectionUtils.isEmpty(list)) {
                    result.setMessage("活动奖励已发放完毕，敬请关注后续精彩活动");
                    result.setState(-1);
                    return result;
                } else {
                    result.setMessage("您已获得活动奖励，请在中奖记录中查看");
                    result.setState(0);
                    return result;
                }
            } else {
                Integer helpGoodId = activity.getHelpGoodId();
                List<Prize> list = prizeRepository.findByUnionIdAndGoodId(vm.getHelpUnionId(), helpGoodId);
                if (CollectionUtils.isEmpty(list)) {
                    result.setMessage("活动奖励已发放完毕，敬请关注后续精彩活动");
                    result.setState(-1);
                    return result;
                } else {
                    result.setMessage("您已获得活动奖励，请在中奖记录中查看");
                    result.setState(0);
                    return result;
                }
            }
        }

    }

    /**
     * 查询订阅消息配置
     * @return
     */
    public List<MsgTemplateInfo> getHelpMessage() {
        return msgTemplateInfoRepository.findAll();
    }
}
